package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;


public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    //dom4j解析核心配置文件
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(inputStream);
        Element documentRootElement = document.getRootElement();
        //封装数据库参数
        List<Element> list = documentRootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        //存储数据源到全局配置对象Configuration
        configuration.setDataSource(comboPooledDataSource);
       //
        List<Element> mapperList = documentRootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            //解析映射文件
            String resourcePath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(resourcePath);
            XMLMapperBuiler xmlMapperBuiler = new XMLMapperBuiler(configuration);
            xmlMapperBuiler.parseXMLConfig(resourceAsStream);
        }
        return configuration;
    }
}
